package myJs.user.data

import myJs.Utils._
import scala.scalajs.js.Dynamic.{global => g}
import org.scalajs.dom.ext.Ajax
import myJs.Implicits._
import myJs.myPkg._
import myJs.tool.Pojo.FilterContentData
import myJs.tool.Tool
import myJs.tool.Tool._
import scalatags.Text.all.s
import myJs.myPkg.jquery._
import org.scalajs.dom.{Element, document}
import shared.Pojo._

import scala.scalajs.js
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._

/**
 * Created by yz on 25/10/2020
 */
object FileViewModal {

  val viewModalId = "viewModal"
  val tableId = "table"

  def init = {
    registerEvent
  }

  def getId = {
    $(s"#${viewModalId} #id").text().trim
  }

  def getKind = {
    $(s"#${viewModalId} #kind").text().trim
  }

  def registerEvent = {
    tableFilterEvent(viewModalId)
    $(s"#${viewModalId}").on("shown.bs.modal", () => {
      FileViewModal.refreshData
    })
  }

  def getUrl = {
    getKind match {
      case "group" => g.jsRoutes.controllers.GroupFileDataController.getFileData().url.toString
      case MetDataKind.name => g.jsRoutes.controllers.MatrixFileDataController.getFileData().url.toString
      case VarInfoDataKind.name => g.jsRoutes.controllers.VarInfoFileDataController.getFileData().url.toString
      case BiomDataKind.name => g.jsRoutes.controllers.BiomFileDataController.getFileData().url.toString
      case _ => g.jsRoutes.controllers.DataController.getFileData().url.toString
    }
  }

  def tableF = {
    val id = getId
    val url = getUrl
    Ajax.get(url = s"${url.noCache}&id=${id}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      rs("array").toJArJDS
    }
  }

  def refreshTable(f: JArJDS => js.Any = (myData) => ()) = {
    val parentId = viewModalId
    val queryMap = Tool.getQueryMap(parentId)
    println(queryMap)
    tableF.map { data =>
      val sortData = DataManage.sortExec(data, queryMap)

      def loopFilter(sortData: JArJDS) = {

        val filterColumns = queryMap.removedAll(List("sort", "order")).filter(_._2.map(_.trim).nonEmpty).keyList

        def loop(acc: JArJDS, elems: List[String]): JArJDS = {
          elems match {
            case Nil => acc
            case y :: ys =>
              val searchV = queryMap(y)
              val trueSearchV = searchV.head
              val fieldName = y.split("\\.")(0)
              val name = y.split("\\.")(1)
              val curFilterData = {
                fieldName match {
                  case "size" => val (minSize, maxSize) = trueSearchV match {
                    case "0KB-100KB" => (0, 100 * 1024)
                    case "100KB-1MB" => (100 * 1024, 1 * 1024 * 1024)
                    case "1MB-10MB" => (1 * 1024 * 1024, 10 * 1024 * 1024)
                  }
                    acc.filter { row =>
                      val size = row(fieldName).toInt
                      size <= maxSize && size >= minSize
                    }
                  case "tags" => acc.filter { row =>
                    Tool.tagMap(row(fieldName)).contains(trueSearchV)
                  }
                  case x if DataManage.timeFieldNames.contains(x) => acc.filter { row =>
                    val dbDate = row(fieldName)
                    if (name == "startTime") {
                      Tool.timeBefore(trueSearchV, dbDate)
                    } else {
                      Tool.timeAfter(trueSearchV, dbDate)
                    }
                  }
                  case _ => acc.filter { row =>
                    row(fieldName).containsIgnoreCase(trueSearchV)
                  }
                }
              }
              loop(curFilterData, ys)
          }
        }

        loop(sortData, filterColumns)
      }

      val filterData = loopFilter(sortData)
      $(s"#${parentId} #${tableId}").bootstrapTable("load", filterData)
      f(data)
    }
  }

  def tableFilterEvent(parentId: String) = {
    Tool.clickHide
    $(document.body).on("click", s"#${parentId} .myOperate", "", (y: Element) => {
      Tool.filterContentShowInModal(y, parentId)
    })
    $(document.body).on("click", s"#${parentId} .mySortLi", "", (y: Element) => {
      Tool.execSort(y, parentId, () => {
        refreshTable()
      })
    })
    $(document.body).on("click", s"#${parentId} .myConfirm", "", (y: Element) => {
      Tool.confirmFilter(y, parentId, () => {
        refreshTable()
      })
    })
    $(document.body).on("click", s"#${parentId} .myHide", "", (y: Element) => {
      Tool.hideFilterContent(y)
    })
    $(document.body).on("click", s"#${parentId} .myRemove", "", (y: Element) => {
      Tool.removeCondition(y, parentId, () => {
        refreshTable()
      })
    })
    $(document.body).on("click", s"#${parentId} .myRemoveSort", "", (y: Element) => {
      Tool.removeSort(y, parentId, () => {
        refreshTable()
      })
    })
  }

  def initFilterContent(name: String, tabId: String = "") = {
    val textSortDatas = List(
      FilterContentData(name, name),
    )
    Tool.initFilterContent(textSortDatas = textSortDatas,
      parentId = s"${tabId}")
  }

  def refreshData = {
    val index = layer.load(1, Tool.layerOptions.shade(js.Array("0.1", "#fff")))
    val url = getUrl
    Ajax.get(url = s"${url.noCache}&id=${getId}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val columnNamesOp =rs.get("columnNames").map{columnNames=>
        columnNames.toJArS
      }
      $(s".myFileData").hide()
      columnNamesOp.map{columnNames=>
        val name = columnNames.head
        initFilterContent(name, viewModalId)
        val columns = columnNames.map { columnName =>
          val basicOptions = ColumnOptions.field(columnName).title(columnName).sortable(true)
          val fmt = columnName
          columnName match {
            case x if name == x => basicOptions.
              sortable(false).operateable(true)
            case _ => basicOptions
          }
        }
        val options = TableOptions.columns(columns).pagination(true).fixedColumns(true).fixedNumber(1).data(rs("array")).
          locale(Tool.getBTLanguage)
        $(s"#${viewModalId} #${tableId}").bootstrapTable("destroy").bootstrapTable(options)
        $(s"#${viewModalId} #${tableId}").parents(".myFileData").show()
      }.getOrElse{
        val str=rs("str").toString
        $(s".myFileData.myStrData").text(str).show()
      }
      layer.close(index)
    }
  }


}
